﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Harkon.AppServer.cOne.Service;
using System.Net.Sockets;
using System.Net;
using log4net;

namespace Harkon.AppServer.cOne.Cluster
{
    public interface IMulticastSender : IService
    {
        void SendMessage(MulticastMessage message);
    }

    public class MulticastSender : AbstractService, IMulticastSender
    {
        public ProtocolHelper Helper { get; set; }
        private static ILog logger = LogManager.GetLogger(typeof(MulticastSender));

        public string GroupIpAddress { get; set; }
        public int PortNumber { get; set; }

        private UdpClient sender { get; set; }

        private IPEndPoint GroupEndPoint { get; set; }

        public override bool Init()
        {
            if (base.Init())
            {
                logger.InfoFormat("Starting sender socket on {0}:{1}...", GroupIpAddress, PortNumber);
                sender = new UdpClient();
                GroupEndPoint = new IPEndPoint(IPAddress.Parse(GroupIpAddress), PortNumber);

                logger.Info("...sender socket connected");

                return true;
            }
            return false;
        }

        public override bool Start()
        {
            if (base.Start())
            {
                //Send multicast packet to inform others about new arrival
                MulticastMessage hiMessage = Helper.CreateMessage(MessageType.Hello);
                SendMessage(hiMessage);

                return true;
            }
            return false;
        }

        public override bool Stop()
        {
            if (base.Stop())
            {
                sender.Close();

                return true;
            }
            return false;
        }

        public void SendMessage(MulticastMessage message)
        {
            byte[] messageBytes = message.ToByteArray(); 
            sender.Send(messageBytes, messageBytes.Length, GroupEndPoint);
        }

    }
}
